package cn.liujianbo.example.base.classloader;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 实现类的热加载
 *
 * @author 刘建波
 * @date 2021-12-02 21:26
 */
public class HotReloader {

    private static Map<String, Long> fileSnapshot = new ConcurrentHashMap<>();

    public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException, InterruptedException {
        // 读取当前包下的文件
        File file = new File(HotReloader.class.getResource("").getPath());
        File[] files = file.listFiles();
        for (File f : files) {
            fileSnapshot.put(f.getPath(), f.lastModified());
        }

        URL url = file.toURI().toURL();
        URLClassLoader classLoader = new URLClassLoader(new URL[]{url});

//        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
//        scheduledExecutorService.scheduleAtFixedRate(new WatchDog(classLoader, fileSnapshot), 3, 3, TimeUnit.SECONDS);

        Class<?> myLog = classLoader.loadClass(HotReloader.class.getPackage().getName()+ "." + "MyLog");

        while (true) {
            MyLog log = (MyLog) myLog.newInstance();
            System.out.println(log.getClass().getClassLoader());
            log.log();
            TimeUnit.SECONDS.sleep(2);
        }
    }
}
